﻿#include"stdafx.h"
#include "ServerDB.h"

bool ServerDB::Index_Create(string tname, string db,string column, string &msg) {
	cur_db = db.c_str();
	if (cur_db == "") {
		msg = "Please choose a database !";
		return false;
	}

	CString  tbPath; tbPath = L"data\\" + cur_db + L"\\" + cur_db + L".tb";
	char *buf = new char[strlen(tname.c_str()) + 1];
	strcpy(buf, tname.c_str());
	if (!IsTable(tbPath, buf)) {
		msg = "Incorrect table name !";
		return false;
	}
	delete buf;

	CString DBPath, Ctname; 
	Ctname = tname.c_str();
	DBPath = L"data\\" + cur_db + L"\\" + Ctname;
	Table_Tdf tdf; 
	vector<Table_Tdf>vec_tdf;
	bool flag = false;
	int pos = 0, size = 0;

	//改变tdf文件
	file.Open(DBPath + L".tdf", CFile::modeReadWrite | CFile::typeBinary, NULL);
	while (file.Read(&tdf, sizeof(tdf)) != 0) {
		string field = tdf.name;
		if (field == column) {
			flag = true;
			pos = tdf.order;
			size = tdf.param;
			tdf.index = true;
			int s = sizeof(tdf);
			file.Seek(-s, file.current);
			file.Write(&tdf, sizeof(tdf));
		}
		vec_tdf.push_back(tdf);
	}
	file.Close();
	if (!flag) {
		msg = "wrong Column!";
		return false;
	}

	int lenth = vec_tdf.back().order + vec_tdf.back().param;
	
	string auth = db + "_" + tname + "_" + column;
	indexM.ReProduceIndex(CStringTostring(DBPath),column,auth,pos,lenth,size);

	

	msg = "successful !";
	return true;
}
